<template>
  <!-- 搜索结果展示仪表盘 -->
  <div id="panel" v-if="panelShow"></div>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { inject, watch, computed, ref, provide, onMounted } from 'vue'

const route = useRoute()
const mapData = inject('mapAMap')
const panelShow = ref(false)
const isShow = inject('isShow')
const placeSearch = ref(null)
const clearSearchMarkers = inject('clearSearchMarkers')

// 清除搜索标记的方法
const clearPlaceSearch = () => {
  if (placeSearch.value) {
    placeSearch.value.clear()
    panelShow.value = false
  }
}
// 在组件挂载时，将清除方法赋值给父组件提供的引用
onMounted(() => {
  if (clearSearchMarkers) {
    clearSearchMarkers.value = clearPlaceSearch
  }
})
// 计算属性来检查地图是否准备好
const isMapReady = computed(() => {
  return mapData && mapData.map && mapData.map.value && mapData.AMap && mapData.AMap.value
})

// 分开监听 inputValue
watch(isShow.inputValue, (newValue) => {
  if (newValue === '') {
    panelShow.value = false
    isShow.searchResultVisible.value = true
  }
})

// 监听地图准备状态和路由参数
watch(
  [isMapReady, () => route.params.type],
  ([ready, newType]) => {
    if (ready && newType) {
      clearPlaceSearch()
      initPanel(newType)
      panelShow.value = true
    }
  },
  { immediate: true }
)

function initPanel(newType) {
  if (!isMapReady.value) {
    console.error('地图还未初始化完成')
    return
  }

  //构造地点查询类
  placeSearch.value = new mapData.AMap.value.PlaceSearch({
    pageSize: 20, // 单页显示结果条数
    pageIndex: 1, // 页码
    city: '010', // 兴趣点城市
    citylimit: false, //是否强制限制在设置的城市内搜索
    map: mapData.map.value, // 展现结果的地图实例
    panel: 'panel', // 结果列表将在此容器中进行展示。
    autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
  })
  //关键字查询
  placeSearch.value.search(newType)
}

provide('clearPlaceSearch', clearPlaceSearch)
</script>
<style lang="scss">
#panel {
  width: 360px;
  max-height: 500px;
  overflow-y: auto;
  /* 添加垂直滚动条 */
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 12px;
  position: fixed;
  top: 60px;
  left: 10px;
  z-index: 999;
}

.amap-search-panctrl {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  width: 360px;
  color: #0f89f5;
  font-size: 14px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 12px;
  position: fixed;
  top: 56px;
  left: 10px;
  z-index: 999;
}
</style>
